<?php

/**
 * Description of Util
 *
 * @author HEO
 */
class Util {

    public static function app() {
        return Yii::app();
    }

    public static function user() {
        return Yii::app()->user;
    }

    public static function module($m){
        return Util::app()->getModule($m);
    }

    public static function language() {
        return Yii::app()->language;
    }

    public static function webroot() {
        return Yii::getPathOfAlias('webroot');
    }
 	public static function baseUrl() {
        return Yii::app()->baseUrl;
    }
	public static function themeUrl() {
        return  Yii::app()->theme->baseUrl;
    }
    public static function homeUrl() {
        return Yii::app()->homeUrl;
    }
	public static function hostUrl() {
		return "http://" . $_SERVER['HTTP_HOST'].self::baseUrl();
	}


	public static function baseUpload($folder = null) {
        return self::baseUrl() . '/uploads' . (($folder != '') ? ('/' . $folder) : '');
    }
	public static function pathUpload($folder = null) {
        return self::webroot() . '/uploads' . (($folder != '') ? ('/' . $folder) : '');
    }
	public static function baseTheme($folder = null) {
        return self::themeUrl() . (($folder != '') ? ('/' . $folder) : '');
    }



    public static function clientScript() {
        return Yii::app()->clientScript;
    }

    public static function registerScriptFile($url, $position = CClientScript::POS_HEAD) {
        Util::clientScript()->registerScriptFile($url, $position);
    }

    public static function registerScript($id, $script, $position = CClientScript::POS_READY) {
        Util::clientScript()->registerScript($id, $script, $position);
    }

    public static function registerCssFile($url, $media = '') {
        Util::clientScript()->registerCssFile($url, $media);
    }

    public static function registerCss($id, $css, $media='') {
        Util::clientScript()->registerCss($id, $css, $media='');
    }

	public static $arrayActive = array(1 => 'Active', 0 => 'Deactive');
    public static $arrayCofirm = array(1 => 'Yes', 0 => 'No');


	public static function getImageExist($folder, $imgNm) {
		$check = false;
		$path  = self::pathUpload($folder) . '/' . $imgNm;
		if (file_exists($path) && $imgNm != '')
		    $pathView = self::baseUpload($folder) . '/' . $imgNm;
		else{
			$pathView = self::baseUpload() . '/no_image.jpg';
		}
		return $pathView;
    }

    public static function t($string, $params = array(), $category = 'Label') {
        Yii::import('application.modules.admin.models.Translate');

        $language = Yii::app()->language;
        $cache_id = sprintf('translations_%s_%s', $language, $category);

        $messages = false;
        if (Yii::app()->cache)
            $messages = Yii::app()->cache->get($cache_id);

        if ($messages === false) {
//            $translations = Translate::model()->findAll('category = :category AND language_code = :language', array(
//                ':category' => $category,
//                ':language' => $language
//                    ));
//            $messages = array();
//            foreach ($translations as $row) {
//                $messages[$row->message] = $row->translation;
//            }

            if (Yii::app()->cache)
                Yii::app()->cache->set($cache_id, $messages, Yii::app()->params['caching_time']);
        }

        if (isset($messages[$string]))
            return strtr($messages[$string], $params);
        else
            return strtr($string, $params);
    }

    public static function toAscii($str) {
        $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
        $str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
        $str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
        $str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
        $str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
        $str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
        $str = preg_replace("/(đ)/", 'd', $str);
        $str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
        $str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
        $str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
        $str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
        $str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
        $str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
        $str = preg_replace("/(Đ)/", 'D', $str);
        $str = ereg_replace("[-.,]", "", $str);
        $str = ereg_replace("[^ A-Za-z0-9]", " ", $str);
        return $str;
    }

    public static function toAlias($str) {
        $str = self::toAscii($str);
        $word_list = split(' ', $str);
        $str = '';
        foreach ($word_list as &$word) {
            if ($word != '')
                $str .= '-' . $word;
        }
        return trim(strtolower(substr($str, 1, strlen($str))));
    }

    public static function getFileExtension($filename) {
        return strtolower(substr($filename, strpos($filename, '.') + 1));
    }

    public static function generalCode($lastID, $prefixChar) {
        if ($lastID != null) {
            $prefix = "";
            while (strlen($lastID) < 4) {
                $prefix .= 0;
                $lastID = $prefix . $lastID;
                $prefix = "";
            }

            return $prefixChar . $lastID;
        }
    }

    /**
     * check user role
     */
    public static function isAllowProcess($userID, $role, $controllerName, $controllerAction){
        if ($role == 'Administrator')
            return 1;
        else
//            $role = UserRole::model()->findAll(array(
//                'select' => 'controller_action',
//                'condition' => 'user_id = :userID AND controller_name = :controllerName AND role = :role AND controller_action = :controllerAction AND status = 1',
//                'params' => array(
//                    ':userID' => $userID,
//                    ':role' => $role,
//                    ':controllerAction' => $controllerAction,
//                    ':controllerName' => $controllerName
//                )
//            ));
        return $role;
    }

//    public static function getUserRole($userID){
//        Yii::import('application.modules.admin.models.AuthAssignment');
//        $userRole = AuthAssignmentBase::model()->find(array(
//            'condition' => 'userid = :userID',
//            'params' => array(
//                ':userID' => $userID
//            ),
//        ));
//
//        if ($userRole)
//            return $userRole->itemname;
//        else
//            return null;
//    }

    /**
     * list all user except admin for create role access in UserRoleController
     */
    public static function listUsers(){
        $users = User::model()->findAll(array(
            'select' => 't.id, CONCAT(profile.lastname,\' \', profile.firstname) as fullname',
            'join' => 'JOIN profile ON profile.user_id = t.id JOIN auth_assignment ON auth_assignment.userid = t.id',
            'condition' => 'auth_assignment.itemname <> \'Administrator\''
        ));

        return CHtml::listData($users, 'id', 'fullname');
    }

    /**
     * list all role name
     */
//    public static function listRolesName(){
//        $role = User::model()->findAll(array(
//            'select' => 'auth_assignment.itemname',
//            'join' => 'JOIN auth_assignment ON  auth_assignment.userid = t.id',
//            'condition' => 'auth_assignment.itemname <> \'Administrator\'',
//        ));
//
//        return CHtml::listData($role, 'itemname', 'itemname');
//    }

    /**
     * Get User fullname by is
     */
    public static function userFullNameByID($id){
        Yii::import('application.modules.user.models.Profile');
        $model = $model = Profile::model()->findByPk($id);

        if($model === NULL)
            return Util::t("Null Value");

        return CHtml::link($model->lastname." ".$model->firstname, Yii::app()->createUrl('user/admin/view', array('id' => $model->user_id)), array('target' => '_blank'));
    }

    public static function getImageName($image){
            $imgNm = preg_replace('/\/|™|®|©|\s|\'|-/', '_', $image);
            return $imgNm;
    }

}
